package com.suxin.plugin.intergration.manager.finder;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;

/**
 * @author Tang
 * @classname PropertiesPluginDescriptorFinder
 * @description [  ]
 * @date 2022/7/4 21:59
 */
public class PropertiesPluginDescriptorFinder implements PluginDescriptorFinder{

    public static final String DEFAULT_PROPERTIES_FILE_NAME = "plugin.properties";

    public static final String PLUGIN_ID = "Plugin-Id";
    public static final String PLUGIN_DESCRIPTION = "Plugin-Description";
    public static final String PLUGIN_CLASS = "Plugin-Class";
    public static final String PLUGIN_VERSION = "Plugin-Version";
    public static final String PLUGIN_PROVIDER = "Plugin-Provider";
    public static final String PLUGIN_DEPENDENCIES = "Plugin-Dependencies";
    public static final String PLUGIN_REQUIRES = "Plugin-Requires";
    public static final String PLUGIN_LICENSE = "Plugin-License";

    protected String propertiesFileName;

    public PropertiesPluginDescriptorFinder() {
        this(DEFAULT_PROPERTIES_FILE_NAME);
    }

    public PropertiesPluginDescriptorFinder(String fileName) {
        this.propertiesFileName = fileName;
    }

    @Override
    public boolean isApplicable(Path pluginPath) {
        return Files.exists(pluginPath) && (Files.isDirectory(pluginPath));
    }

    @Override
    public PluginDescriptor find(Path pluginPath) {
        Properties properties = readProperties(pluginPath);
        return createPluginDescriptor(properties);
    }

    private PluginDescriptor createPluginDescriptor(Properties properties) {
        DefaultPluginDescriptor pluginPluginDescriptor = getPluginPluginDescriptor();
        // 解析
        return pluginPluginDescriptor;
    }

    DefaultPluginDescriptor getPluginPluginDescriptor() {
        return new DefaultPluginDescriptor();
    }

    private Properties readProperties(Path pluginPath) {
        Path propertiesPath = pluginPath.resolve(propertiesFileName);
        Properties properties = new Properties();
        try (InputStream inputStream = Files.newInputStream(propertiesPath)) {
            properties.load(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return properties;
    }
}